#include<iostream>
#include<string>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main(int argc,char* argv[])
{
    if(argc!=3){
        std::cout<<"Usage: "<<argv[0]<<" <server_ip> <port>"<<std::endl;
        return 1;
    }
    int port=std::stoi(argv[2]);
    std::string ip = argv[1];
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0){
        std::cout<<"create socket error"<<std::endl;
        return 2;
    }
    struct sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr(ip.c_str());
    //建立连接
    int n = ::connect(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
    
    if(n<0){
        std::cout<<"connect error"<<std::endl;
        return 3;
    }
    while(true){
        std::string send_buf;
        std::cout<<"please input message:"<<std::endl;
        std::getline(std::cin,send_buf);
        ssize_t n = ::write(sockfd,send_buf.c_str(),send_buf.size());
        if(n<0){
            std::cout<<"send error"<<std::endl;
            break;
        }
        char recv_buf[1024];
        n = ::read(sockfd,recv_buf,sizeof(recv_buf)-1);
        if(n<0){
            std::cout<<"recv error"<<std::endl;
            break;
        }
        recv_buf[n] = 0;
        std::cout<<"recv message:"<<recv_buf<<std::endl;
    }
    ::close(sockfd);

    return 0;
}